﻿using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

using Cookbook.Services.Core.Domain;
using Cookbook.Services.Host.ExceptionHandling;

namespace Cookbook.Services.Host
{
    /// <summary>
    ///   Exposes our data model as a REST-based service.
    /// </summary>
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ExceptionShieldingBehavior]
    public class RestService : DataService<RestContext>
    {
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.UseVerboseErrors = true;
            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
            config.SetServiceOperationAccessRule("*", ServiceOperationRights.AllRead);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }

        [WebGet]
        public IQueryable<Recipe> FindRecipes(string partialTitle, string partialDescription, int minimumRating)
        {
            return from recipe in CurrentDataSource.Recipes
                   where (partialTitle.Length == 0 || (recipe.Title.Contains(partialTitle)))
                   where (partialDescription.Length == 0 || (recipe.Description.Contains(partialDescription)))
                   where (recipe.Rating == null) || (recipe.Rating > minimumRating)
                   select recipe;
        }

        [WebGet]
        public bool IsUnique(string recipeTitle)
        {
            return !CurrentDataSource.Recipes.Any(r => r.Title == recipeTitle);
        }
    }
}